package wyu.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dto.Result;
import com.entity.Category;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import wyu.mapper.CategoryMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.util.RedisConstant.CATEGORY_KEY;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Result getList() {
        //查询redis缓存
        String categoriesJson = stringRedisTemplate.opsForValue().get(CATEGORY_KEY);
        //redis存在category数据
        if (StrUtil.isNotBlank(categoriesJson)) {
            System.out.println("从redis返回了category");
            List<Category> shopTypeList = JSONUtil.toList(JSONUtil.parseArray(categoriesJson), Category.class);
            return Result.ok(shopTypeList);
        }
        //redis不存在category数据
        List<Category> list = query().list();
        if (list.isEmpty()){
            return Result.fail(900,"未知错误-_-!");
        }
        //4.添加到redis缓存
        stringRedisTemplate.opsForValue().set(CATEGORY_KEY, JSONUtil.toJsonStr(list),30, TimeUnit.MINUTES);
        return Result.ok(list);
    }

    @Override
    public Result categoryDel(int id) {
        boolean isRemove = removeById(id);
        if (!isRemove){
            return Result.fail(900,"删除失败");
        }
        return Result.ok();
    }

    @Override
    public Result idUsed(int id) {
        Category category = getById(id);
        if (category==null){
            return Result.ok();
        }
        return Result.fail(306,"（贴吧）类别（id）已存在");
    }

    @Override
    public Result categoryAdd(int id, String name, String describe) {
        Category category = new Category();
        category.setId(id);
        category.setName(name);
        if (describe == null){
            describe = "";
        }
        category.setDescribe(describe);
        boolean save = save(category);
        if (!save){
            return Result.fail(900,"添加失败");
        }
        return Result.ok();
    }
}
